package com.xiejun.netty;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.util.ArrayList;
import java.util.List;

/**
 * 简单的ChannelPipeline实现
 */
public class ChannelPipeline implements ChannelHandler {
    
    private final List<ChannelHandler> handlers = new ArrayList<>();
    
    /**
     * 添加处理器到管道
     * @param handler 处理器
     * @return 当前管道实例
     */
    public ChannelPipeline addLast(ChannelHandler handler) {
        handlers.add(handler);
        return this;
    }
    
    @Override
    public void channelRead(SocketChannel channel, ByteBuffer buffer) throws IOException {
        // 依次调用所有处理器的channelRead方法
        for (ChannelHandler handler : handlers) {
            // 为每个处理器创建一个新的缓冲区副本，避免数据竞争
            ByteBuffer bufferCopy = ByteBuffer.allocate(buffer.capacity());
            bufferCopy.put(buffer);
            bufferCopy.flip();
            handler.channelRead(channel, bufferCopy);
        }
    }
    
    @Override
    public void channelConnected(SocketChannel channel) throws IOException {
        // 依次调用所有处理器的channelConnected方法
        for (ChannelHandler handler : handlers) {
            handler.channelConnected(channel);
        }
    }
    
    @Override
    public void channelDisconnected(SocketChannel channel) throws IOException {
        // 依次调用所有处理器的channelDisconnected方法
        for (ChannelHandler handler : handlers) {
            handler.channelDisconnected(channel);
        }
    }
}